package com.dp.service.impl;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pub.SysProperty;
import com.dp.service.impl3.BaseImpl;
import com.dp.util.InterUtil;



@Service
@Transactional
public class CatalogServiceImpl extends BaseImpl {

	
//	public void createOldCatalog(int channeltype,String catalogName, String channelid){
////		TChannels channels =getChannel(buttonid);
//		// insert news_catalog
//		NewsCatlog newcatalog = new NewsCatlog();
//		newcatalog.setCatlogname(catalogName);
//		newcatalog.setCatlogversion(getMaxCatalogVersion()+1);
//		newcatalog.setCatlogcarrer("1");
//		newcatalog.setIsnowpublish(0);
//		newcatalog.setCreatetime(new Date());
//		Set<NewsExtendsFirstchannel> newsExtendsFirstchannelSet = new HashSet();
//		NewsExtendsFirstchannel nef = (NewsExtendsFirstchannel) this.get(NewsExtendsFirstchannel.class, Integer.valueOf(channelid));
//		newsExtendsFirstchannelSet.add(nef);
//		newcatalog.setNewsExtendsFirstchannelSet(newsExtendsFirstchannelSet);
//		this.persist(newcatalog);
//		Set<NewsCatlog> newsCatlogSet = new HashSet();
//		newsCatlogSet.add(newcatalog);
//		nef.setNewsCatlogSet(newsCatlogSet);
//		this.persist(nef);
//		
//	}

//	public void createCatalog(int channeltype,String catalogName, String selectbuttons){
//		
//		//insert t_channels
//		TChannels channels = new TChannels();
//		String channel_id = BaseBean.ObjectToString(KeyGenerator.getInstance().getNextKeyValue("t_channels"));
//		//this.updateHql("update MainKey mk set mk.keyValue= '"+channel_id.split("_")[1]+"' where mk.keyName='t_channels'");
//		channels.setChannelId(channel_id);
//		channels.setChannelName(catalogName);
//		channels.setFunctionName("FIRST");
//		channels.setCreatedDate(new Date());
//		channels.setLevel("0");
//		channels.setPreviousId(channel_id);
//		channels.setPrimalId(channel_id);
//		this.persist(channels);
//		
//		
//		// insert news_catalog
//		NewsCatlog newcatalog = new NewsCatlog();
//		newcatalog.setCatlogname(catalogName);
//		newcatalog.setCatlogversion(getMaxCatalogVersion()+1);
//		newcatalog.setCatlogcarrer("1");
//		//newcatalog.setIsnowpublish(2);
//		newcatalog.setIsnowpublish(0);
//		newcatalog.setCreatetime(new Date());
//		this.persist(newcatalog);
//
//		//insert news_catlog_channel
//		//insert news_extends_firstchannel
//		NewsExtendsFirstchannel nef = new NewsExtendsFirstchannel();
//		
//		nef.setChannelId(channels);
//		nef.setChanneltype(channeltype);
//		nef.setLastupdate(new Date());
//		Set<NewsCatlog> newsCatlogSet = new HashSet();
//		newsCatlogSet.add(newcatalog);
//		nef.setNewsCatlogSet(newsCatlogSet);
//		this.persist(nef);
//		//insert news_extends_firstchannel_buttons
//		
//		String buttonlist = selectbuttons;
//        if(buttonlist!=null && !buttonlist.equals(""))
//        {
//	    	String[] c_id_strList=buttonlist.split(",");
//	    	for(int i=0;i<c_id_strList.length;i++)
//	        {
//	            String bid = c_id_strList[i];
//	            NewsExtendsFirstchannelButtons nfb = new NewsExtendsFirstchannelButtons();
//	            NewsExtendsFirstchannelButtonsPK nfbpk = new NewsExtendsFirstchannelButtonsPK(nef.getChannelid(),Integer.valueOf(bid));
//	            nfb.setNewsExtendsFirstchannelButtonsPK(nfbpk);
//	            nfb.setButtonorder(i+1);
//	            this.persist(nfb);
//	        }
//        }
//        this.emr.flush();
//		
//	}
	
//	public List getAllButtons(){
//		String hql = "SELECT n FROM NewsButtons n where n.buttontype='3' or n.buttontype='6'";
//		List buttonlist = getQueryList(hql);
//		return buttonlist;
//		
//	}
//	
//	public Integer getMaxCatalogVersion(){
//		String hql = "SELECT max(n.catlogversion) FROM NewsCatlog n";
////		List list = getQueryList(hql);
//		Object version = getSingleResult(hql);
//		int maxversion =1;
//		if(version !=null){
//			maxversion=(Integer) version;
//		} 
//		return maxversion;
//	}
//	
//	public List getAllVersion(){
//		
//		String hql = "SELECT n FROM NewsCatlog n order by n.isnowpublish, n.catlogversion desc, n.createtime desc ";
//		List buttonlist = getQueryList(hql);
//		return buttonlist;
//		
//	}
	
	/**
	 * catlog平台
	 * @return
	 */
//    public List getAllVersion2(){
//		
//		String hql = "SELECT n FROM NewsCatlog n where isnowpublish!=1 order by n.isnowpublish, n.catlogversion desc, n.createtime desc ";
//		List buttonlist = getQueryList(hql);
//		return buttonlist;
//		
//	}
//	public Long getAllVersionCount(){
//		
//		String hql = "SELECT count(n) FROM NewsCatlog n order by n.isnowpublish desc, n.catlogversion desc, n.createtime desc ";
//		Long count = (Long) getSingleResult(hql);
//		return count;
//		
//	}
//	
//	public List getAllVersionCount(int firstrow, int maxrow){
//		
//		String hql = "SELECT n FROM NewsCatlog n order by case when n.isnowpublish=1 then 1 end desc,case when n.isnowpublish=2 then 1 end desc,n.isnowpublish desc, n.catlogversion desc, n.createtime desc ";
//		List list = getQueryList(hql, firstrow, maxrow);
//		return list;
//		
//	}
//	
//	public void rePublish(int catalog){
//		NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catalog);
//		catlog.setIsnowpublish(2);
//		catlog.setCatlogversion(getMaxCatalogVersion()+1);
//		this.save(catlog);
//	}
	
	
	/**
	 * 定时器刷新缓存publishcatlog时调用
	 */
	public void rePublishcatlogURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
    	    //url=System.getProperty("flushportalurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     	
            url+="action/server!publishcatlog.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                    log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
            	  } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
                  
        }
      
	 }
	
	/**
	 * 刷新缓存publishcatlog
	 * 设置默认目录，更改多平台信息时调用
	 */
	public void rePublishAllcatlogURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     	
            url+="action/server!publishallcatlog.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
            	  } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
                  
        }
      
	 }
	
	/**
	 * 刷新缓存publishcatlog
	 * 目录发布时调用
	 */
	public void rePublishcatlogURL(int catlogid){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     	
            url+="action/server!publishcatlog.do?catlogid="+catlogid;
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
            	  } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
                  
        }
      
	 }
	/**
	 * 刷新缓存publishtitle时
	 * 5分钟立即发布频道定时器和3点，17点更新频道缓存定时器调用
	 */
	public void rePublishtitleURL(String channelidlist){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     
            url+="action/server!publishtitle.do?channelidlist="+channelidlist;
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info((ret != 200?InterUtil.rb.getString("src.refPorErr"):InterUtil.rb.getString("src.refPorSuc"))+"：返回码："+ret+url);
   		         } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
           
        }
      
	 }
	/**
	 * 清除服务器缓存
	 * 5分钟立即发布频道定时器和3点，17点更新频道缓存定时器调用
	 */
	public void clearserver(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     
            url+="action/aserver!clear.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info((ret != 200?InterUtil.rb.getString("src.refPorErr"):InterUtil.rb.getString("src.refPorSuc"))+"：返回码："+ret+url);
   		         } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
           
        }
      
	 }
	
	public void rePublishHdNewsURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
		    url=SysProperty.getPrep("hdnews_pubilshurl"+i);
	        if(url==null||"".equals(url)){
	        	return;  
	        }
	        try{
				URL testUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
				conn.setRequestMethod("POST");
				int ret = conn.getResponseCode();
				conn.disconnect();
				log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
	        } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    
        }
	 }
	
	/**
	 * 加载缓存reloadWeather时调用
	 */
	public void reloadWeatherURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     
            url+="action/server!reloadWeather.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
   		         } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
           
        }
      
	 }
	/**
	 * 加载新的系统参数到缓存时调用:reloadsysparam
	 */
	public void reloadSysparamURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     
            url+="action/server!reloadsysparam.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
   		         } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
           
        }
      
	 }
//	public TChannels getChannel(String buttonid){
//		String hql = "select tc from NewsButtons nb,TChannels tc where nb.buttontext = tc.channelName and nb.buttonid='"+buttonid+"'";
//		TChannels channel = (TChannels) getSingleResult(hql);
//		return channel;
//		
//	}
	
//	public List getFirstChannels(){
//		String hql = "select new com.dp.pojo.FirstChannels(tc.channelId, nef.channelid,"+
//			"tc.serviceCode, tc.channelName, tc.functionName,tc.status, tc.ordered) from TChannels tc, NewsExtendsFirstchannel nef where tc.channelId = nef.channelId and nef.channelid is not null";
//		List channellist = getQueryList(hql);
//		return channellist;
//		
//	}
//	
//	public List getCatalogView(String channelid){
//		String hql = "SELECT new com.dp.pojo.CatalogView(nef.channel_id, nfb.buttonid,nb.buttonname,nct.channelid)  FROM NewsExtendsFirstchannel nef,NewsExtendsFirstchannelButtons nfb,NewsButtons nb, "+
//					"NewsContenttype nct WHERE nef.channelid='12' AND nef.channelid = nfb.channelid "+
//					"AND nfb.buttonid = nb.buttonid AND nb.buttoncontenttype = nct.newscontenttype ";
//		List channellist = getQueryList(hql);
//		return channellist;
//		
//	}
//	
//	public List getLastCatalogView(String channelid){
//		String hql = "SELECT new com.dp.pojo.CatalogView(nef.channel_id, nfb.buttonid,nb.buttonname,nct.channelid)  FROM NewsExtendsFirstchannel nef,NewsExtendsFirstchannelButtons nfb,NewsButtons nb, "+
//					"NewsContenttype nct WHERE nef.channelid='12' AND nef.channelid = nfb.channelid "+
//					"AND nfb.buttonid = nb.buttonid AND nb.buttoncontenttype = nct.newscontenttype ";
//		List channellist = getQueryList(hql);
//		return channellist;
//		
//	}


	/**
	 * 目录下线
	 * @param catalogid
	 */
//	public void Offline(int catalogid) {
//		NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catalogid);
//		catlog.setIsnowpublish(3);
//		this.save(catlog);
//	}
//	
//	/**
//	 * 是否为默认目录
//	 * @param catalogid
//	 */
//	public boolean isDefaulted(int catalogid) {
//		NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catalogid);
//		if(catlog.getIsnowpublish()==1){
//			//默认再发布
//			catlog.setCatlogversion(getMaxCatalogVersion()+1);
//			this.save(catlog);
//			return true;
//		}
//		return false;
//	}
	
	/**
	 * 设为默认目录
	 * @param catalogid
	 */
//	public void SetDefaulted(int catalogid) {
//		String hql = "update NewsCatlog n set n.isnowpublish=0 where n.isnowpublish=1";
//		updateHql(hql);
//		NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catalogid);
//		catlog.setIsnowpublish(1);
//		catlog.setCatlogversion(getMaxCatalogVersion()+1);
//		this.save(catlog);
//	}

	/**
	 * 平台未关联catlog且catlog状态为发布，则修改为下线
	 */
//	public void updateCatlogOfflined(Integer catlogid) {
//		String hql = "select ncp from NewsCatlogPlatform ncp where ncp.catlogid.catlogid="+catlogid;
//		List list = getQueryList(hql);
//		if(list.size()>0){
//			return ;
//		}
//		hql = "select nc.isnowpublish from NewsCatlog nc where nc.catlogid="+catlogid;
//		Object obj = getSingleResult(hql);
//		int isnowpublish =0;
//		if(obj !=null){
//			isnowpublish=(Integer) obj;
//		} 
//		//为发布状态，设置为下线状态3
//		if(isnowpublish==2){
//			NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catlogid);
//			catlog.setIsnowpublish(3);
//			this.save(catlog);
//		}
//		
//	}
//	
//	@SuppressWarnings("unchecked")
//	public int updateHql(String hql) {
//		Query query = emr.createQuery(hql);
//		int iCode=0;
//		iCode=query.executeUpdate();
//		emr.flush();
//		return iCode;
//	}

}
